<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>${product.name} - 绿蜂巢农产品系统</title>
    <link rel="stylesheet" href="static/css/styles.css">
</head>
<body>
<!-- 引入头部导航 -->
<jsp:include page="header.jsp" />

<main class="container">
    <!-- 商品ID存在性校验 -->
    <c:if test="${empty product.id}">
        <div class="error-container">
            <h3 class="error-title">错误</h3>
            <p class="error-desc">商品信息异常，ID不能为空</p>
        </div>
    </c:if>

    <c:if test="${not empty product.id}">
        <!-- 商品图片 -->
        <div class="detail-image">
            <img src="<c:url value="/static/photo/${product.photo}"/>"
                 alt="${product.name}"
                 class="product-image">
        </div>

        <!-- 商品信息 -->
        <div class="product-info card">
            <h1 class="product-title">${product.name}</h1>

            <div class="product-price">
                ¥${product.price}
            </div>

            <!-- 数量选择器 -->
            <div class="quantity-selector">
                <label for="quantity">数量：</label>
                <button type="button" onclick="decreaseQuantity()">-</button>
                <input type="number" id="quantity" value="1" min="1" max="${product.stock}">
                <button type="button" onclick="increaseQuantity()">+</button>
            </div>

            <!-- 购买按钮 -->
            <div class="purchase-buttons">
                <button class="add-to-cart-btn" onclick="addToCart(${product.id})">加入购物车</button>
                <button class="buy-now-btn" onclick="buyNow(${product.id})">立即购买</button>
            </div>

            <div class="supplier-info">
                <div class="supplier-logo"></div>
                <div>
                    <div class="supplier-address">${supplier.address}</div>
                </div>
            </div>

            <div class="product-features">
                    ${product.features}
            </div>
        </div>

        <!-- 选项卡导航 -->
        <div class="tabs">
            <div class="tab active" onclick="showTab(1)">商品详情</div>
            <div class="tab" onclick="showTab(2)">规格参数</div>
            <div class="tab" onclick="showTab(3)">用户评价</div>
        </div>

        <!-- 选项卡内容 -->
        <div class="tab-content active" id="tab1">
            <div class="card">
                <h3 class="section-title">商品详情</h3>
                <p>${product.features}</p>
            </div>
        </div>

        <div class="tab-content" id="tab2">
            <div class="card">
                <h3 class="section-title">规格参数</h3>
                <table class="spec-table">
                    <tr>
                        <td>商品名称</td>
                        <td>${product.name}</td>
                    </tr>
                    <tr>
                        <td>类别</td>
                        <td>${product.category}</td>
                    </tr>
                    <tr>
                        <td>价格</td>
                        <td>¥${product.price}</td>
                    </tr>
                    <tr>
                        <td>库存</td>
                        <td>${product.stock}</td>
                    </tr>
                    <tr>
                        <td>供应商电话</td>
                        <td>${supplier.phone}</td>
                    </tr>
                </table>
            </div>
        </div>

        <div class="tab-content" id="tab3">
            <div class="card">
                <h3 class="section-title">用户评价</h3>
                <p>暂无评价</p>
            </div>
        </div>
    </c:if>
</main>

<!-- 引入底部导航 -->
<jsp:include page="footer.jsp" />

<script>
    // 应用上下文路径
    const contextPath = "${pageContext.request.contextPath}";

    // 选项卡切换逻辑
    function showTab(tabIndex) {
        const tabContents = document.querySelectorAll('.tab-content');
        tabContents.forEach(pane => pane.classList.remove('active'));
        document.getElementById('tab' + tabIndex).classList.add('active');

        const tabButtons = document.querySelectorAll('.tab');
        tabButtons.forEach(button => button.classList.remove('active'));
        event.currentTarget.classList.add('active');
    }

    // 数量选择器逻辑
    function increaseQuantity() {
        const input = document.getElementById('quantity');
        const current = parseInt(input.value) || 1;
        const max = parseInt(input.max) || 99;
        if (current < max) input.value = current + 1;
    }

    function decreaseQuantity() {
        const input = document.getElementById('quantity');
        const current = parseInt(input.value) || 1;
        const min = parseInt(input.min) || 1;
        if (current > min) input.value = current - 1;
    }

    // 加入购物车功能（增强参数校验）
    function addToCart(productId) {
        // 强制转换为数字并校验
        productId = Number(productId);
        if (isNaN(productId) || productId <= 0) {
            alert('错误：商品ID无效，请刷新页面重试');
            console.error('addToCart: 无效商品ID', productId);
            return;
        }

        const quantity = parseInt(document.getElementById('quantity').value);
        if (isNaN(quantity) || quantity <= 0) {
            alert('请输入有效的购买数量');
            document.getElementById('quantity').focus();
            return;
        }

        const maxStock = parseInt(document.getElementById('quantity').max);
        if (quantity > maxStock) {
            alert(`数量不能超过库存数量 ${maxStock}`);
            document.getElementById('quantity').value = maxStock;
            return;
        }

        // 构建请求参数
        const formData = new FormData();
        formData.append('productId', productId.toString());
        formData.append('quantity', quantity.toString());

        // 发送请求
        const addButton = document.querySelector('.add-to-cart-btn');
        const originalText = addButton.textContent;
        addButton.disabled = true;
        addButton.textContent = '添加中...';

        fetch(contextPath + '/cart/add', {
            method: 'POST',
            body: formData
        })
            .then(res => {
                if (!res.ok) throw new Error(`HTTP错误 ${res.status}`);
                return res.text().then(text => {
                    try { return JSON.parse(text); }
                    catch { throw new Error('响应格式错误'); }
                });
            })
            .then(data => {
                if (data.success) {
                    alert('已添加到购物车');
                    updateCartCount(data.cartCount);
                    document.getElementById('quantity').value = 1;
                } else {
                    alert('添加失败：' + (data.message || '未知错误'));
                }
            })
            .catch(err => {
                console.error('添加购物车请求失败', err);
                alert('操作失败：' + err.message);
            })
            .finally(() => {
                addButton.disabled = false;
                addButton.textContent = originalText;
            });
    }

    // 立即购买功能
    function buyNow(productId) {
        const quantity = parseInt(document.getElementById('quantity').value);
        if (isNaN(quantity) || quantity <= 0) {
            alert('请输入有效的购买数量');
            return;
        }
        addToCart(productId);
        setTimeout(() => {
            window.location.href = contextPath + '/checkout';
        }, 1000);
    }

    // 更新购物车数量
    function updateCartCount(count) {
        const cartCount = document.querySelector('.cart-count');
        if (cartCount) {
            cartCount.textContent = count || 0;
            cartCount.style.display = (count > 0) ? 'inline' : 'none';
        }
    }

    // 页面初始化
    document.addEventListener('DOMContentLoaded', () => {
        const quantityInput = document.getElementById('quantity');
        if (!quantityInput.value || quantityInput.value <= 0) {
            quantityInput.value = 1;
        }

        quantityInput.addEventListener('change', function() {
            let val = parseInt(this.value) || 1;
            const min = parseInt(this.min) || 1;
            const max = parseInt(this.max) || 99;
            this.value = Math.max(min, Math.min(max, val));
        });
    });
</script>
</body>
</html>
